// 发送请求后让按钮处于loading状态，请求结束后移除loading并以Message的形式弹出请求错误的信息，用法：
// <el-button v-request="{请求函数}"></el-button>
import { Message } from '@/element'

const requestDirective = {
  inserted(el, binding) {
    el.addEventListener('click', function() {
      el.classList.add('is-loading')
      const loadingEl = document.createElement('i')
      loadingEl.classList.add('el-icon-loading')
      el.insertBefore(loadingEl, el.firstChild)
      binding
        .value()

        .then(() => {
          el.classList.remove('is-loading')
          loadingEl.remove()
        })
        .catch((err) => {
          if (err.message) {
            Message({
              message: err.message,
              type: 'error',
              duration: 5 * 1000
            })
          }

          el.classList.remove('is-loading')
          loadingEl.remove()
        })
    })
  }
}

export default requestDirective
